"""
测试Celery任务
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from apps.itineraries.tasks import send_reminder_notifications, cleanup_old_reminders
import logging

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = '测试Celery任务是否正常工作'

    def add_arguments(self, parser):
        parser.add_argument(
            '--task',
            type=str,
            choices=['send_reminders', 'cleanup', 'all'],
            default='all',
            help='要测试的任务类型'
        )

    def handle(self, *args, **options):
        task_type = options['task']
        
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write(self.style.SUCCESS('Celery任务测试'))
        self.stdout.write(self.style.SUCCESS('=' * 60))
        
        try:
            # 检查Celery是否可用
            try:
                from celery import current_app
                self.stdout.write(self.style.SUCCESS('✓ Celery已安装'))
            except ImportError:
                self.stdout.write(self.style.ERROR('✗ Celery未安装'))
                return
            
            # 检查Redis连接
            try:
                from django.core.cache import cache
                cache.set('test_key', 'test_value', 10)
                test_value = cache.get('test_key')
                if test_value == 'test_value':
                    self.stdout.write(self.style.SUCCESS('✓ Redis连接正常'))
                else:
                    self.stdout.write(self.style.WARNING('⚠ Redis连接异常'))
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'✗ Redis连接失败: {str(e)}'))
                return
            
            # 测试发送提醒任务
            if task_type in ['send_reminders', 'all']:
                self.stdout.write('\n测试发送提醒任务...')
                try:
                    # 直接调用任务函数（同步执行，用于测试）
                    result = send_reminder_notifications()
                    if result.get('success'):
                        self.stdout.write(
                            self.style.SUCCESS(
                                f"✓ 发送提醒任务执行成功，发送了 {result.get('sent_count', 0)} 条提醒"
                            )
                        )
                    else:
                        self.stdout.write(
                            self.style.ERROR(f"✗ 发送提醒任务执行失败: {result.get('error')}")
                        )
                except Exception as e:
                    self.stdout.write(self.style.ERROR(f'✗ 发送提醒任务异常: {str(e)}'))
            
            # 测试清理旧提醒任务
            if task_type in ['cleanup', 'all']:
                self.stdout.write('\n测试清理旧提醒任务...')
                try:
                    # 直接调用任务函数（同步执行，用于测试）
                    result = cleanup_old_reminders()
                    if result.get('success'):
                        self.stdout.write(
                            self.style.SUCCESS(
                                f"✓ 清理旧提醒任务执行成功，清理了 {result.get('deleted_count', 0)} 条旧提醒"
                            )
                        )
                    else:
                        self.stdout.write(
                            self.style.ERROR(f"✗ 清理旧提醒任务执行失败: {result.get('error')}")
                        )
                except Exception as e:
                    self.stdout.write(self.style.ERROR(f'✗ 清理旧提醒任务异常: {str(e)}'))
            
            # 检查Celery Worker状态
            self.stdout.write('\n检查Celery Worker状态...')
            try:
                from celery import current_app
                inspect = current_app.control.inspect()
                active_workers = inspect.active()
                if active_workers:
                    self.stdout.write(self.style.SUCCESS(f'✓ 发现 {len(active_workers)} 个活跃的Worker'))
                    for worker_name, tasks in active_workers.items():
                        self.stdout.write(f'  - {worker_name}: {len(tasks)} 个活跃任务')
                else:
                    self.stdout.write(self.style.WARNING('⚠ 未发现活跃的Worker'))
                    self.stdout.write(self.style.WARNING('  请确保Celery Worker正在运行'))
            except Exception as e:
                self.stdout.write(self.style.WARNING(f'⚠ 无法检查Worker状态: {str(e)}'))
                self.stdout.write(self.style.WARNING('  请确保Celery Worker正在运行'))
            
            # 检查Celery Beat状态
            self.stdout.write('\n检查Celery Beat状态...')
            self.stdout.write(self.style.INFO('提示: Celery Beat需要单独启动'))
            self.stdout.write(self.style.INFO('  使用命令: celery -A travel_plan beat'))
            
            self.stdout.write('\n' + '=' * 60)
            self.stdout.write(self.style.SUCCESS('测试完成'))
            self.stdout.write('=' * 60)
            
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'测试过程中发生错误: {str(e)}'))
            import traceback
            self.stdout.write(traceback.format_exc())


